<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

class Order extends Backend
{
  // 开启关联查询
  protected $relationSearch = true;

  protected $OrderProductModel;
  protected $BusinessModel;

  public function __construct()
  {
    parent::__construct();

    $this->model = model('Order.Order');
    $this->OrderProductModel = model('Order.Product');
    $this->BusinessModel = model('Business.Business');

    // 注入前置数据
    $this->view->assign("statusList", $this->model->statuslist());
  }

  public function index()
  {
    //设置过滤方法
    $this->request->filter(['strip_tags', 'trim']);

    // 判断是否有Ajax请求
    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      $total = $this->model
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->count();

      $list = $this->model
        ->with(['express', 'business'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      $result = [
        'rows' => $list,
        'total' => $total
      ];

      return json($result);
    }

    // 输出视图
    return $this->view->fetch();
  }
  // 发货
  public function deliver($ids = null)
  {
    $row = $this->model->find($ids);

    if (!$row) {
      $this->error('订单不存在');
    }

    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');

      // 封装数据
      $data = [
        'id'          => $ids,
        'expressid'   => $params['expressid'], // 快递公司ID
        'expresscode' => $params['expresscode'], // 快递单号
        'shipmanid'   => $this->auth->id,
        'status'      => 2 // 设置状态为已发货
      ];

      // 定义验证器
      $validate = [
        [
          'expressid'   => 'require',
          'expresscode' => 'require|unique:order'
        ],
        [
          'expressid.require'   => '配送物流未知',
          'expresscode.unique'  => '配送物流单号已存在，请重新输入',
          'expresscode.require' => '请输入配送物流单号'
        ]
      ];

      // 更新数据
      $result = $this->model->validate(...$validate)->isUpdate(true)->save($data);

      if ($result === false) {
        $this->error($this->model->getError());
      } else {
        $this->success('发货成功');
      }
    }

    // 查询物流公司的数据
    $ExpData = model('Express')->column('id,name');

    $this->assign([
      'ExpData' => $ExpData,
      'row' => $row
    ]);

    return $this->fetch();
  }
  // 详情
  public function info($ids = null)
  {
    // 关联查询
    $row = $this->model->with(['business', 'express', 'address' => ['provinces', 'citys', 'districts'], 'sale', 'review', 'dispatched'])->find($ids);

    if (!$row) {
      $this->error('订单不存在');
    }

    // 订单商品
    $OrderProductData = $this->OrderProductModel->with(['products'])->where(['orderid' => $ids])->select();

    $this->assign([
      'row' => $row,
      'OrderProductData' => $OrderProductData
    ]);

    return $this->view->fetch();
  }
  // 退货审核
  public function refund($ids = null)
  {
    $ids = $ids ?: $this->request->param('ids', 0, 'trim');

    $row = $this->model->find($ids);

    if (!$row) {
      $this->error('订单不存在');
    }

    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');

      if (empty($params['examinereason']) && $params['refund'] == 0) {
        $this->error('请填写不同意退货的原因');
      }

      // 同意仅退款
      if ($params['refund'] === '1' && $row['status'] === '-1') {
        $business = $this->BusinessModel->find($row['busid']);

        if (!$business) {
          $this->error('用户不存在');
        }

        // 开启事务
        $this->BusinessModel->startTrans();
        $this->model->startTrans();

        // 更新用户余额
        $businessData = [
          'id' => $business['id'],
          'money' => bcadd($row['amount'], $business['money'], 2)
        ];

        $businessRes = $this->BusinessModel->isUpdate(true)->save($businessData);

        if ($businessRes === false) {
          $this->error('更新用户余额失败');
        }

        // 更新订单的状态
        $OrderData = [
          'id' => $ids,
          'status' => -4,
        ];

        $orderRes = $this->model->isUpdate(true)->save($OrderData);

        if ($orderRes === false) {
          $this->BusinessModel->rollback();
          $this->error('更新订单状态失败');
        }

        if ($businessRes === false || $orderRes === false) {
          $this->BusinessModel->rollback();
          $this->model->rollback();
          $this->error('同意退款失败');
        } else {
          $this->BusinessModel->commit();
          $this->model->commit();
          $this->success('同意退款成功');
        }
      }

      // 同意退款退货
      if ($params['refund'] === '1' && $row['status'] === '-2') {
        // 封装数据
        $data = [
          'id' => $ids,
          'status' => -3
        ];

        $result = $this->model->isUpdate(true)->save($data);

        if ($result === false) {
          $this->error();
        } else {
          $this->success();
        }
      }

      // 不同意退货
      if ($params['refund'] === '0') {
        // 封装数据
        $data = [
          'id' => $ids,
          'status' => -5,
          'examinereason' => $params['examinereason']
        ];

        $result = $this->model->isUpdate(true)->save($data);

        if ($result === false) {
          $this->error();
        } else {
          $this->success();
        }
      }
    }

    $this->assign([
      'row' => $row
    ]);

    return $this->view->fetch();
  }
  // 软删除
  public function del($ids = null)
  {
    $ids = $ids ?: $this->request->params('ids', '', 'trim');

    $row = $this->model->where('id', 'in', $ids)->select();

    if (!$row) {
      $this->error('请选择需要删除的订单');
    }

    $result = $this->model->destroy($ids);

    if ($result === false) {
      $this->error('删除失败');
    } else {
      $this->success('删除成功');
    }
  }
  // 回收站
  public function recyclebin()
  {
    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      // 过滤请求参数中的html标签和取消两边你空白
      $this->request->filter(['strip_tags', 'trim']);
      // 获取查询参数
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();


      $total = $this->model
        ->onlyTrashed()
        ->where($where)
        ->count();

      $list = $this->model
        ->onlyTrashed()
        ->with(['express', 'business'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      // var_dump($this->model->getLastSql());
      // exit;

      $result = [
        'rows' => $list,
        'total' => $total,
      ];

      return json($result);
    }
  }
  // 还原
  public function restore($ids = null)
  {

    $ids = $ids ?: $this->request->params('ids', '', 'trim');

    $row = $this->model->onlyTrashed()->where('id', 'in', $ids)->select();

    if (!$row) {
      $this->error('请选择需要还原的数据');
    }

    $result = $this->model->onlyTrashed()->where('id', 'in', $ids)->update(['deletetime' => null]);

    if ($result === false) {
      $this->error('还原失败');
    } else {
      $this->success('还原成功');
    }
  }
  // 真实删除
  public function destroy($ids = null)
  {
    $ids = $ids ?: $this->request->params('ids', '', 'trim');

    $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

    if (!$row) {
      $this->error('请选择需要删除的数据');
    }
    
    // 开启事务
    $this->model->startTrans();
    $this->OrderProductModel->startTrans();

    $orderProductData = $this->OrderProductModel->where(['orderid' => ['in', $ids]])->column('id');

    $orderRes = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->delete();

    if ($orderRes === false) {
      $this->error($this->model->getError());
      exit;
    }

    $orderProductRes = $this->OrderProductModel->where(['id' => ['in', $orderProductData]])->delete();

    if ($orderProductRes === false) {
      $this->model->rollback();
      $this->error($this->OrderProductModel->getError());
      exit;
    }

    if ($orderRes === false || $orderProductRes === false) {
      $this->OrderProductModel->rollback();
      $this->model->rollback();
      $this->error('销毁失败');
      exit;
    } else {
      $this->model->commit();
      $this->OrderProductModel->commit();
      $this->success('销毁成功');
      exit;
    }
  }
}
